package com.example.blog.controller;

import com.example.blog.domain.*;
import com.example.blog.dto.publicDto.PageDto;
import com.example.blog.mapper.UsersMapper;
import com.example.blog.note.LogInfo;
import com.example.blog.note.NoToken;
import com.example.blog.note.Permissions;
import com.example.blog.service.LoginService;
import com.example.blog.service.impl.OperationalLogsServiceImpl;
import com.example.blog.utils.JwtUtils;
import com.example.blog.utils.MyMail;
import com.example.blog.utils.RedisStorage;
import com.fasterxml.jackson.core.JsonProcessingException;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

// 登录
@RestController
@Transactional
@Slf4j
@RequestMapping("/front")
public class LoginController extends BaseController{
    private final LoginService loginService;
    private final MyMail myMail;
    private final RedisStorage redisStorage;

    @Autowired
    public LoginController( LoginService loginService,
                            MyMail myMail,RedisStorage redisStorage){
        this.loginService=loginService;
        this.myMail=myMail;
        this.redisStorage=redisStorage;
    }

    //测试接口
    @NoToken
    @PostMapping("/wxPost")
    public Response wxPost(@RequestBody PageDto pageDto) {
        Map<String,String> stringStringMap = new HashMap<>();
        stringStringMap.put("result_Post","我是LOW_B");
        stringStringMap.put("result_Date",pageDto.toString());
        return new Response(Response.SUCCEED_CODE,"测试接口",stringStringMap);
    }

    @NoToken
    @GetMapping("/wxGet")
    public Response wxGet() {
        Map<String,String> stringStringMap = new HashMap<>();
        stringStringMap.put("result_GET","我是LOW_B");
        return new Response(Response.SUCCEED_CODE,"测试接口",stringStringMap);
    }



    //登录
    @NoToken
    @PostMapping("/userLogin")
    @LogInfo(value = "用户登录")
    public Response login(@RequestBody Users users) {
        if (!redisStorage.checkEnrollCaptcha(users.getCaptcha_id(), users.getCaptcha())) {
            return new Response(Response.ERROR_CODE, "验证码错误", null);
        }
        try {
            return loginService.login(users);
        } catch (RuntimeException e) {
            //返回错误信息
            return new Response(Response.ERROR_CODE,  e.getMessage(),null);
        } catch (JsonProcessingException e) {
            return new Response(Response.ERROR_CODE, "系统繁忙，请稍后再试", null);
        }
    }


    //退出登录
    @GetMapping("/user/logout")
    @LogInfo(value = "退出登录")
    public Response logout(){
        String token = getHttpInfo().getHeader("token");
        Claims claims = JwtUtils.checkToken(token);
        boolean result = false;
        result = redisStorage.SignOut(String.valueOf(claims.get("uid")));
        return new Response(Response.SUCCEED_CODE, "退出登录成功", result);
    }


    //获取验证码
    @NoToken
    @GetMapping("/captcha")
    @LogInfo(value = "登录获取验证码")
    public Response loginCaptcha() {
        String captcha = myMail.myMailCaptcha();
        UuId uuId = new UuId();
        uuId.setUuidValue(captcha);
        uuId.setId(String.valueOf(UUID.randomUUID()));
        redisStorage.insertCaptcha(uuId.getId(), captcha, 60);
        return new Response(Response.SUCCEED_CODE, "登录验证码", uuId);
    }

    //删除错误的验证码
    @NoToken
    @GetMapping("/delete/captcha/{id}")
    @LogInfo(value = "删除验证码")
    public Response deleteLoginCaptcha(@PathVariable("id") String id) {
        return new Response(Response.SUCCEED_CODE, "删除验证码", redisStorage.deleteCaptcha(id));
    }

    //Admin登录
    @Permissions("/front/adminLogin")
    @PostMapping("/adminLogin")
    @LogInfo(value = "用户登录")
    @NoToken
    public Response adminLogin(@RequestBody Users users) {
        if (!redisStorage.checkEnrollCaptcha(users.getCaptcha_id(), users.getCaptcha())) {
            return new Response(Response.ERROR_CODE, "验证码错误", null);
        }
        try {
            return loginService.login(users);
        } catch (RuntimeException e) {
            //返回错误信息
            return new Response(Response.ERROR_CODE, e.getMessage(),null );
        } catch (JsonProcessingException e) {
            return new Response(Response.ERROR_CODE, "系统繁忙，请稍后再试", null);
        }
    }

    //注销账号验证码
    @GetMapping("/deleteAuto/captcha/{email}")
    @LogInfo(value = "注销账号验证码")
    public Response deleteAutoCaptcha(@PathVariable("email") String email) throws MessagingException {
        String captcha = myMail.myMailCaptcha();
        UuId uuId = new UuId();
        uuId.setUuidValue(captcha);
        uuId.setId(String.valueOf(UUID.randomUUID()));
        redisStorage.insertCaptcha(uuId.getId(), captcha, 60);
        myMail.sendSimpleMail(
                "验证码",
                email,
                "<h3 style='color:red'> 注销验证码：" + captcha+ "</h3><br/>",true);
        return new Response(Response.SUCCEED_CODE, "注销账号验证码", uuId.getId());
    }


}
